import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Select, Tooltip } from 'antd';
import FuzzyQueryStore from '@/components/FuzzyQueryStore';
import DebounceMultipleSelect from '@/components/DebounceMultipleSelect';
import { customTrimFunc } from '@/utils/utils.jsx';
import { queryTakeUserList, queryAreaCode, queryStoreFactoryList, selectStoreAreasByName } from './service';
import { isEmpty, find } from 'lodash';
import styles from './index.module.less';

const { Option } = Select;

const ModalForm = ({ initKey, offlinePaymentShow, handleSearch, handleFilter }) => {
  const [form] = Form.useForm();
  const [userData, setUserData] = useState([]); // 拿货员列表
  const [refundUserData, setRefundUserData] = useState([]); // 退货员列表

  const [loading, setLoading] = useState(false);

  useEffect(() => {
    handleUserList();
    handleRefundUserList();
  }, []);

  useEffect(() => {
    form.resetFields();
  }, [initKey]);

  //拿货员列表
  const handleUserList = async (username) => {
    const { data, success } = await queryTakeUserList(
      customTrimFunc({ username, current: 1, size: 20, businessType: 3 })
    );
    if (success) {
      setUserData(data);
    }
  };

  //退货员列表
  const handleRefundUserList = async (username) => {
    const { data, success } = await queryTakeUserList(
      customTrimFunc({ username, current: 1, size: 20, businessType: 4 })
    );
    if (success) {
      setRefundUserData(data);
    }
  };

  // 点击查询按钮
  const onFinish = (val) => {
    const data = find(userData, (item) => {
      return item.id == val.takeUserId;
    });
    const refundData = find(refundUserData, (item) => {
      return item.id == val.refundUserId;
    });
    const param = {
      ...val,
      takeUserId: data ? data.id : undefined,
      refundUserId: refundData ? refundData.id : undefined,
    };
    handleSearch(customTrimFunc(param));
  };

  const onReset = () => {
    form.resetFields();
    handleSearch();
    handleUserList('');
    handleRefundUserList('');
  };

  //渲染交接员工
  const renderSubUser = (item) => {
    if (item.name) {
      if (item.account) {
        return item.name + '(' + item.account + ')';
      } else {
        return item.name;
      }
    } else {
      return '';
    }
  };

  function fetchAreaCode(areaCode) {
    return new Promise(async (resolve, reject) => {
      setLoading(true);
      const { data, success } = await queryAreaCode({ areaCode });
      setLoading(false);
      if (success && data?.length) {
        const newArr = [];
        data.map(item => {
          newArr.push({
            label: item.name,
            value: item.name,
          })
        })
        resolve(newArr);
      } else {
        reject();
      }
    })
  }

  //获取门店区域
  function fetchStoreArea(storeArea) {
    return new Promise(async (resolve, reject) => {
      setLoading(true);
      const { data, success } = await selectStoreAreasByName({ storeArea });
      setLoading(false);
      if (success && data?.length) {
        const newArr = [];
        data.map(item => {
          newArr.push({
            label: item,
            value: item,
          })
        })
        resolve(newArr);
      } else {
        reject();
      }
    })
  }

  const optionUserList =
    !isEmpty(userData) &&
    userData.map((item) => (
      <Option key={item.id}>
        <Tooltip title={renderSubUser(item)}>{renderSubUser(item)}</Tooltip>
      </Option>
    ));
  const optionRefundUserList =
    !isEmpty(refundUserData) &&
    refundUserData.map((item) => (
      <Option key={item.id}>
        <Tooltip title={renderSubUser(item)}>{renderSubUser(item)}</Tooltip>
      </Option>
    ));

  return (
    <Form
      layout="inline"
      form={form}
      onFinish={onFinish}
      name="store-search-form"
      size='default'
    // initialValues={{...query}}
    // style={{marginBottom:'8px'}}
    >

      <div className={styles.filter}>
        <Form.Item name="merchantAreaCode">
          <Select placeholder="城市" allowClear style={{ width: '210px' }}>
            {
              APP_TITLE == '找家纺' ?
                <Option value="NT">南通</Option>
                :
                <>
                  <Option value="CS">常熟</Option>
                  <Option value="ZL">织里</Option>
                </>
            }
          </Select>
        </Form.Item>

        <Form.Item name="storeId">
          <FuzzyQueryStore placeholder="请输入供应商" queryData={queryStoreFactoryList} width="210px" />
        </Form.Item>

        <Form.Item name="shopCode">
          <Input placeholder="请输入档口号" style={{ width: '210px' }} />
        </Form.Item>

        <Form.Item name="storeArea" style={{ width: '210px' }}>
          <DebounceMultipleSelect
            showSearch
            allowClear
            needFetchFirst
            labelInValue={false}
            placeholder="请选择门店区域"
            notFoundContent={loading ? '加载中' : '暂无数据'}
            fetchOptions={fetchStoreArea}
          />
        </Form.Item>

        <Form.Item name="shopAddress">
          <Input placeholder="请输入门店地址" style={{ width: '210px' }} />
        </Form.Item>

        <Form.Item name="shopName">
          <Input placeholder="请输入门店名称" style={{ width: '210px' }} />
        </Form.Item>

        <Form.Item name="shopRemark">
          <Input placeholder="请输入门店备注" style={{ width: '210px' }} />
        </Form.Item>

        <Form.Item name="takeUserId">
          <Select
            showSearch
            placeholder="请选择拿货员"
            filterOption={false}
            onSearch={handleUserList}
            allowClear
            style={{ width: '210px' }}
          >
            {optionUserList}
          </Select>
        </Form.Item>

        <Form.Item name="refundUserId">
          <Select
            showSearch
            placeholder="请选择退货员"
            filterOption={false}
            onSearch={handleRefundUserList}
            allowClear
            style={{ width: '210px' }}
          >
            {optionRefundUserList}
          </Select>
        </Form.Item>

        <Form.Item name="shopArea">
          <DebounceMultipleSelect
            showSearch
            allowClear
            needFetchFirst
            labelInValue={false}
            placeholder="请选择区域编码"
            notFoundContent={loading ? '加载中' : '暂无数据'}
            fetchOptions={fetchAreaCode}
            style={{ width: '210px' }}
          />
        </Form.Item>

        <Form.Item name="autoPush">
          <Select placeholder="是否自动推送打印" allowClear style={{ width: '210px' }}>
            <Option value="1">已开启</Option>
            <Option value="0">已关闭</Option>
          </Select>
        </Form.Item>

        <Form.Item label="" colon={false}>
          <Button htmlType="submit" type="primary" style={{ marginRight: "8px" }}>搜索</Button>
          <Button onClick={onReset}>重置</Button>
          <Button type='link' onClick={handleFilter}>展示已选供应商</Button>
        </Form.Item>
      </div>
    </Form>
  );
};

export default ModalForm;
